//
//  SpecialCustomerController.m
//  ELife
//
//  Created by xiaozhi on 11-5-18.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "SpecialCustomerController.h"
#import "SpecialCustomerCell.h"
#import "ELifeAppDelegate.h"
#import "GDataXMLNode.h"
#import "GTMBase64.h"
#import "Parter.h"
#import "WebViewController.h"

@implementation SpecialCustomerController
@synthesize tableView = _tableView;

#pragma mark - network
// 请求特约商户列表
- (void)requestPartnerList
{
    
    /* 请求地址: /ofcard.php
     请求参数: action  => online_order
     user_id  => 用户id
     version	 => 客户端版本号
     goods_id	 => 游戏ID（即商品ID） 6-7位数字
     goods_num  => 商品数量
     game_user_id => 游戏玩家帐号
     game_area  => 游戏所在区，无填空
     game_srv  =>  游戏所在服务器
     money =>   支付金额，用于校验
     */
    ELifeAppDelegate *app = [ELifeAppDelegate App];
    [app showProgressDialog:@"请稍后"];
    
    NSString *host =  [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil];
    NSString *urlStr = [host stringByAppendingString:@"partner.php"];
    
    static NSString *action = @"get_partner_list";
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSURL URLWithString:urlStr], @"requestPartnerFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:3];
    [param setObject:action forKey:@"action"];
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    [[app httpRequestPoint]openUrl:dic
                         postParam:param target:self];
}


- (void)requestPartnerFinished:(NSData *)response
{
    ELifeAppDelegate *app = [ELifeAppDelegate App];
    
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:response] options:0 error:nil];
    GDataXMLElement* rootElement = [doc rootElement];
    NSLog(@"--------rootElement:%@", rootElement);
    GDataXMLElement* bodyElement = [[rootElement elementsForName:@"body"]objectAtIndex:0];
    NSLog(@"--------body:%@", bodyElement);
    
    //某个具体节点的文本内容
    GDataXMLElement* partnersElement = [[bodyElement elementsForName:@"partners"]objectAtIndex:0];
    NSLog(@"--------partners:%@", partnersElement);
    
    NSArray *partnersArr = [partnersElement children];

    _partnersList = [[NSMutableArray alloc]initWithCapacity:[partnersArr count]];
    
    for (int index = 0; index < [partnersArr count]; index++) {
        GDataXMLElement *item = [partnersArr objectAtIndex:index];
        
        Parter *parter = [[Parter alloc]init];
        parter.name = [[[item elementsForName:@"name"]objectAtIndex:0]stringValue];
        parter.webUrlStr = [[[item elementsForName:@"webview"]objectAtIndex:0]stringValue];
        
        // 生成占位图片 并且请求图片
        NSString *imgUrl = [[[item elementsForName:@"img"]objectAtIndex:0]stringValue];
        parter.img = [UIImage alloc];
        [[app httpRequestPoint]getImageDataByUrl:imgUrl forUIImage:parter.img delegate:self];
        
        [_partnersList addObject:parter];
    }
    
    [app hideProgressDialog];
}

/*
 refresh img
 */
- (void)refreshImage
{
    [_tableView reloadData];
}


#pragma markend

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self requestPartnerList];
    }
    return self;
}

- (void)dealloc
{
    [_tableView release];
    [_partnersList release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
}
*/

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_partnersList count] / 2;
}



// fill cell
-(void)fillCell:(SpecialCustomerCell *)cell rowIndex:(NSInteger)row
{
//    if (row == 2 || row == 4) {
//        [cell.categroyView setBackgroundImage:[UIImage imageNamed:@"1-12.png"] forState:UIControlStateNormal];
//    }
    NSInteger firstIndex = row * 2;
    NSInteger secondIndex = firstIndex + 1;
    
    Parter *parter1 = [_partnersList objectAtIndex:firstIndex];
    Parter *parter2 = [_partnersList objectAtIndex:secondIndex];
    
    [cell.specialCustomerView1 setBackgroundImage:parter1.img forState:UIControlStateNormal];
    [cell.specialCustomerView2 setBackgroundImage:parter2.img forState:UIControlStateNormal];
    
    [cell.specialCustomerView1 setTag:firstIndex];
    [cell.specialCustomerView2 setTag:secondIndex];
    
    [cell.specialCustomerView1 addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
    [cell.specialCustomerView2 addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
}

-(void)action:(id)sender
{
    UIView *actionView = (UIView *)sender;
    NSInteger index = actionView.tag;
    
    Parter *parter = [_partnersList objectAtIndex:index];
    NSString *urlStr = parter.webUrlStr;
    
    UIViewController *nextController = [[WebViewController alloc]initWithUrl:urlStr];
    [self.navigationController pushViewController:nextController animated:YES];
    [nextController release];
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell"; 
    SpecialCustomerCell *cell = (SpecialCustomerCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        static NSString *nibName = @"SpecialCustomerCell";
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:nibName owner:self options:nil];
        cell = [array objectAtIndex:0];
    }
    
    [self fillCell:cell rowIndex:indexPath.row];
    return cell;
}

@end
